/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * SpelPlan.java
 *
 * Created on 2010-jan-20, 13:30:45
 */
package exmtgproj;

import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;

/**
 * Load Deck, laddar ett deck av en fil som ligger i decks mappen, filen måste ha ändelsen .xml
 * Load all Decks, laddar ett deck för varje fil i decks mappen som har ändelsen .xml
 * Chose Deck, väljer ett sparat deck
 * Show Decks, visar alla deck som är sparade + hur många kort det är i varje
 * Remove Deck, tar bort ett deck från listan
 *
 * Alla decks laddas när programmet startas och sparas när det avslutas
 *
 * Sort Active Deck by..., sorterar litan efter valda attribut, om inputen inte startar med en siffra sorteras decket efter de attribut som skrivits in
 * Shuffle Active Deck, blandar decket
 * @author marcus ahlen
 */
public class MainFrame extends javax.swing.JFrame implements Statics {

    static javax.swing.JPanel prev; //Preview
    static javax.swing.JPanel spel; //SpelPlan
//get local graphics environment
    GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
//get maximum window bounds
    Rectangle maxSize = graphicsEnvironment.getMaximumWindowBounds();
    static final int edgeLimit = 260;   //bredden på jPanels på kanterna av fönstret
    static CardList chosenDeck = null;    //det valda deckets index
    String deckFile = "decks/save.dck"; //filen där alla dcks sparas och laddas från
    ArrayList<CardList> decks = new ArrayList<CardList>();  //listan dit alla decks som laddas sparas i
    /*static {
    System.setProperty("swing.defaultlaf", "org.jvnet.substance.api.skin.SubstanceGeminiLookAndFeel");
    }*/

    /**
     * Initierar fönstret, alla listeners, variabler och laddar in decks mm
     */
    public MainFrame() {
        try {
            loadDecks(deckFile);
        } catch (IOException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        initComponents();
        init2();
        giveUp.setEnabled(false);
        Game.players.add(new Player("gr", chosenDeck));
        prev = preview;
        spel = spelPlan;
    }

    /**
     *
     */
    private void init2() {
        addKeyListener(new KeyListener() {

            public void keyTyped(KeyEvent e) {
                ((SpelPlan) spel).keyTyped(e.getKeyCode(), e.getModifiers());
            }

            public void keyPressed(KeyEvent e) {
                ((SpelPlan) spel).keyPressed(e.getKeyCode(), e.getModifiers());
            }

            public void keyReleased(KeyEvent e) {
                ((SpelPlan) spel).keyReleased(e.getKeyCode(), e.getModifiers());
            }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        leftSide = new javax.swing.JPanel();
        confirmBox = new javax.swing.JPanel();
        players = new javax.swing.JPanel();
        playerUpper = new javax.swing.JPanel();
        playerLower = new javax.swing.JPanel();
        rightSide = new javax.swing.JPanel();
        preview = new Preview();
        spelPlan = new SpelPlan();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        newGame = new javax.swing.JMenuItem();
        giveUp = new javax.swing.JMenuItem();
        jSeparator5 = new javax.swing.JSeparator();
        newPlayer = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JSeparator();
        jMenu4 = new javax.swing.JMenu();
        loadDeck = new javax.swing.JMenuItem();
        loadAll = new javax.swing.JMenuItem();
        changeDeck = new javax.swing.JMenuItem();
        showDecks = new javax.swing.JMenuItem();
        removeDeck = new javax.swing.JMenuItem();
        removeAll = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        shuffle = new javax.swing.JMenuItem();
        sort = new javax.swing.JMenuItem();
        jSeparator4 = new javax.swing.JSeparator();
        quit = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        fullScreen = new javax.swing.JMenuItem();
        jSeparator3 = new javax.swing.JSeparator();
        cardSize = new javax.swing.JMenu();
        jRadioButtonMenuItem1 = new javax.swing.JRadioButtonMenuItem();
        jRadioButtonMenuItem2 = new javax.swing.JRadioButtonMenuItem();
        jRadioButtonMenuItem3 = new javax.swing.JRadioButtonMenuItem();
        jMenu3 = new javax.swing.JMenu();
        about = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                closing(evt);
            }
        });
        addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                formMouseMoved(evt);
            }
        });
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });

        leftSide.setBackground(new java.awt.Color(102, 255, 51));
        leftSide.setMaximumSize(new java.awt.Dimension(edgeLimit,Integer.MAX_VALUE));
        leftSide.setMinimumSize(new java.awt.Dimension(edgeLimit,506));
        leftSide.setPreferredSize(new java.awt.Dimension(edgeLimit,506));

        confirmBox.setBackground(new java.awt.Color(255, 0, 0));
        confirmBox.setMaximumSize(new java.awt.Dimension(edgeLimit,160));
        confirmBox.setMinimumSize(new java.awt.Dimension(edgeLimit,160));
        confirmBox.setPreferredSize(new java.awt.Dimension(edgeLimit,160));

        javax.swing.GroupLayout confirmBoxLayout = new javax.swing.GroupLayout(confirmBox);
        confirmBox.setLayout(confirmBoxLayout);
        confirmBoxLayout.setHorizontalGroup(
            confirmBoxLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 10, Short.MAX_VALUE)
        );
        confirmBoxLayout.setVerticalGroup(
            confirmBoxLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 10, Short.MAX_VALUE)
        );

        players.setBackground(new java.awt.Color(255, 255, 0));
        players.setMaximumSize(new java.awt.Dimension(edgeLimit,Integer.MAX_VALUE));
        players.setMinimumSize(new java.awt.Dimension(edgeLimit,490));
        players.setPreferredSize(new java.awt.Dimension(edgeLimit,490));

        playerUpper.setMinimumSize(new java.awt.Dimension(edgeLimit,players.getHeight()/2));
        playerUpper.setPreferredSize(new java.awt.Dimension(edgeLimit,players.getHeight()/2));

        javax.swing.GroupLayout playerUpperLayout = new javax.swing.GroupLayout(playerUpper);
        playerUpper.setLayout(playerUpperLayout);
        playerUpperLayout.setHorizontalGroup(
            playerUpperLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 10, Short.MAX_VALUE)
        );
        playerUpperLayout.setVerticalGroup(
            playerUpperLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 320, Short.MAX_VALUE)
        );

        playerLower.setMinimumSize(new java.awt.Dimension(edgeLimit,players.getHeight()/2));
        playerLower.setPreferredSize(new java.awt.Dimension(edgeLimit,players.getHeight()/2));

        javax.swing.GroupLayout playerLowerLayout = new javax.swing.GroupLayout(playerLower);
        playerLower.setLayout(playerLowerLayout);
        playerLowerLayout.setHorizontalGroup(
            playerLowerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 10, Short.MAX_VALUE)
        );
        playerLowerLayout.setVerticalGroup(
            playerLowerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 382, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout playersLayout = new javax.swing.GroupLayout(players);
        players.setLayout(playersLayout);
        playersLayout.setHorizontalGroup(
            playersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(playerUpper, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(playerLower, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        playersLayout.setVerticalGroup(
            playersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(playersLayout.createSequentialGroup()
                .addComponent(playerUpper, javax.swing.GroupLayout.DEFAULT_SIZE, 320, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(playerLower, javax.swing.GroupLayout.DEFAULT_SIZE, 382, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout leftSideLayout = new javax.swing.GroupLayout(leftSide);
        leftSide.setLayout(leftSideLayout);
        leftSideLayout.setHorizontalGroup(
            leftSideLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(leftSideLayout.createSequentialGroup()
                .addGroup(leftSideLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(players, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(confirmBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        leftSideLayout.setVerticalGroup(
            leftSideLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, leftSideLayout.createSequentialGroup()
                .addComponent(players, javax.swing.GroupLayout.DEFAULT_SIZE, 708, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(confirmBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        rightSide.setBackground(new java.awt.Color(102, 255, 102));
        rightSide.setMaximumSize(new java.awt.Dimension(edgeLimit,Integer.MAX_VALUE));
        rightSide.setMinimumSize(new java.awt.Dimension(edgeLimit,506));
        rightSide.setPreferredSize(new java.awt.Dimension(edgeLimit,506));

        preview.setMaximumSize(new java.awt.Dimension(edgeLimit,(edgeLimit*17)/12));
        preview.setMinimumSize(new java.awt.Dimension(edgeLimit,(edgeLimit*17)/12));
        preview.setPreferredSize(new java.awt.Dimension(edgeLimit,(edgeLimit*17)/12));

        javax.swing.GroupLayout previewLayout = new javax.swing.GroupLayout(preview);
        preview.setLayout(previewLayout);
        previewLayout.setHorizontalGroup(
            previewLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 10, Short.MAX_VALUE)
        );
        previewLayout.setVerticalGroup(
            previewLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 724, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout rightSideLayout = new javax.swing.GroupLayout(rightSide);
        rightSide.setLayout(rightSideLayout);
        rightSideLayout.setHorizontalGroup(
            rightSideLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(rightSideLayout.createSequentialGroup()
                .addComponent(preview, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        rightSideLayout.setVerticalGroup(
            rightSideLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(preview, javax.swing.GroupLayout.DEFAULT_SIZE, 724, Short.MAX_VALUE)
        );

        spelPlan.setBackground(new java.awt.Color(255, 255, 255));
        spelPlan.setMinimumSize(new java.awt.Dimension(750, 750));
        spelPlan.setPreferredSize(new java.awt.Dimension(1000, 1000));
        spelPlan.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                spelPlanMouseClicked(evt);
            }
        });
        spelPlan.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                spelPlanMouseMoved(evt);
            }
        });
        spelPlan.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                spelPlanKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout spelPlanLayout = new javax.swing.GroupLayout(spelPlan);
        spelPlan.setLayout(spelPlanLayout);
        spelPlanLayout.setHorizontalGroup(
            spelPlanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 756, Short.MAX_VALUE)
        );
        spelPlanLayout.setVerticalGroup(
            spelPlanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 724, Short.MAX_VALUE)
        );

        jMenu1.setText("File");

        newGame.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        newGame.setText("New Game");
        newGame.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newGameActionPerformed(evt);
            }
        });
        jMenu1.add(newGame);

        giveUp.setText("Give Up");
        giveUp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                giveUpActionPerformed(evt);
            }
        });
        jMenu1.add(giveUp);
        jMenu1.add(jSeparator5);

        newPlayer.setText("New Player");
        newPlayer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newPlayerActionPerformed(evt);
            }
        });
        jMenu1.add(newPlayer);
        jMenu1.add(jSeparator2);

        jMenu4.setText("Deck Options");

        loadDeck.setText("Load Deck");
        loadDeck.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loadDeckActionPerformed(evt);
            }
        });
        jMenu4.add(loadDeck);

        loadAll.setText("Load all Decks");
        loadAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loadAllActionPerformed(evt);
            }
        });
        jMenu4.add(loadAll);

        changeDeck.setText("Choose Deck");
        changeDeck.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                changeDeckActionPerformed(evt);
            }
        });
        jMenu4.add(changeDeck);

        showDecks.setText("Show Decks");
        showDecks.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showDecksActionPerformed(evt);
            }
        });
        jMenu4.add(showDecks);

        removeDeck.setText("Remove Deck");
        removeDeck.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeDeckActionPerformed(evt);
            }
        });
        jMenu4.add(removeDeck);

        removeAll.setText("Remove All Decks");
        removeAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeAllActionPerformed(evt);
            }
        });
        jMenu4.add(removeAll);
        jMenu4.add(jSeparator1);

        shuffle.setText("Shuffle Active Deck");
        shuffle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                shuffleActionPerformed(evt);
            }
        });
        jMenu4.add(shuffle);

        sort.setText("Sort Active Deck by...");
        sort.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sortActionPerformed(evt);
            }
        });
        jMenu4.add(sort);

        jMenu1.add(jMenu4);
        jMenu1.add(jSeparator4);

        quit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE, 0));
        quit.setText("Quit");
        quit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                quitActionPerformed(evt);
            }
        });
        jMenu1.add(quit);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Options");

        fullScreen.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F11, 0));
        fullScreen.setText("Full Screen");
        fullScreen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fullScreenActionPerformed(evt);
            }
        });
        jMenu2.add(fullScreen);
        jMenu2.add(jSeparator3);

        cardSize.setText("Card Size");

        jRadioButtonMenuItem1.setText("Small");
        jRadioButtonMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButtonMenuItem1ActionPerformed(evt);
            }
        });
        cardSize.add(jRadioButtonMenuItem1);

        jRadioButtonMenuItem2.setSelected(true);
        jRadioButtonMenuItem2.setText("Default");
        jRadioButtonMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButtonMenuItem2ActionPerformed(evt);
            }
        });
        cardSize.add(jRadioButtonMenuItem2);

        jRadioButtonMenuItem3.setText("Large");
        jRadioButtonMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButtonMenuItem3ActionPerformed(evt);
            }
        });
        cardSize.add(jRadioButtonMenuItem3);

        jMenu2.add(cardSize);

        jMenuBar1.add(jMenu2);

        jMenu3.setText("Help");

        about.setText("About");
        jMenu3.add(about);

        jMenuBar1.add(jMenu3);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(leftSide, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(spelPlan, javax.swing.GroupLayout.DEFAULT_SIZE, 756, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(rightSide, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(rightSide, javax.swing.GroupLayout.DEFAULT_SIZE, 724, Short.MAX_VALUE)
            .addComponent(spelPlan, javax.swing.GroupLayout.PREFERRED_SIZE, 724, Short.MAX_VALUE)
            .addComponent(leftSide, javax.swing.GroupLayout.DEFAULT_SIZE, 724, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseMoved
    }//GEN-LAST:event_formMouseMoved

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
    }//GEN-LAST:event_formKeyPressed
    /**
     * koden i komentarer är för ändring av decks för flera spelare
     * @param evt
     */
    private void changeDeckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_changeDeckActionPerformed
        /*if (Game.players.size() == 0) {
        JOptionPane.showMessageDialog(this, "You must create a player to change it's deck...");
        return;

        } else */ if (decks.size() == 0) {
            JOptionPane.showMessageDialog(this, "Load a deck first...");
            return;
        }
        //String pl = "";
        String[] de = new String[decks.size()];
        //int playar = 0;
        /*for (Player p : Game.players) {
        pl += ++playar + ": " + p.name + "\n";
        }*/

        for (int i = 0; i < de.length; i++) {
            de[i] = decks.get(i).name;
        }


        String s;
        while (true) {
            try {
                /*s = JOptionPane.showInputDialog(pl);
                if (s == null) {
                return;
                }

                playar = Integer.parseInt(s) - 1;
                Game.players.get(playar);*/
                break;

            } catch (Exception e) {
            }
        }

        CardList cl = chooseDeck();
        if (cl == null) {
            return;
        }
        setChosenDeck(cl);

        for (int i = 0; i < chosenDeck.size(); i++) {
            chosenDeck.get(i).initImg();
        }
        SpelPlan.yPrev = 0;
    }//GEN-LAST:event_changeDeckActionPerformed

    private CardList chooseDeck() {
        CardList[] cl = new CardList[decks.size()];
        for (int i = 0; i < decks.size(); i++) {
            cl[i] = decks.get(i);
        }
        spel.getGraphics().dispose();
        prev.getGraphics().dispose();
        return (CardList) JOptionPane.showInputDialog(this, "Choose a deck", "Deck choosing", JOptionPane.PLAIN_MESSAGE, null, cl, chosenDeck);
    }
    private void newPlayerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newPlayerActionPerformed
        JOptionPane.showMessageDialog(this, "NYI");
        /*if (decks.size() == 0) {
        JOptionPane.showMessageDialog(this, "Make a deck first...");
        return;

        } else if (Game.players.size() > 1) {
        JOptionPane.showMessageDialog(this, "You are allready 2 players...");
        return;

        }


        String s = JOptionPane.showInputDialog("What's your name?");
        if (s == null) {
        return;
        }

        String n = s;
        CardList d = null;
        String message = getDecks();
        while (true) {
        try {
        s = JOptionPane.showInputDialog(message);
        if (s == null) {
        return;
        }

        d = decks.get(Integer.parseInt(s) - 1);
        break;

        } catch (Exception e) {
        }
        }
        Game.players.add(new Player(n, d));*/
    }//GEN-LAST:event_newPlayerActionPerformed

    private void closing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closing
        exit();
    }//GEN-LAST:event_closing

    private void removeDeckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeDeckActionPerformed
        if (decks.size() == 0) {
            JOptionPane.showMessageDialog(this, "You don't have any decks to remove...");
            return;

        }
        CardList cl = chooseDeck();
        if (cl == null) {
            return;
        }
        if (cl.equals(cl)) {
            chosenDeck = null;
        }
        decks.remove(cl);
        spel.repaint();
    }//GEN-LAST:event_removeDeckActionPerformed

    private void loadDeckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadDeckActionPerformed
        //load(false);
        JFileChooser file = new JFileChooser();
        file.setFileFilter(new FileFilter() {

            public boolean accept(File f) {
                if (f.isDirectory()) {
                    return true;
                }
                return f.getAbsolutePath().endsWith(".xml") || f.getAbsolutePath().endsWith(".dck");
            }

            @Override
            public String getDescription() {
                return "*.xml, *.dck";
            }
        });
        int i = file.showOpenDialog(this);
        File f = file.getSelectedFile();
        if (f != null) {
            System.out.println(f.getName());
            load(f);
        }
    }//GEN-LAST:event_loadDeckActionPerformed

    private void newGameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newGameActionPerformed
        JOptionPane.showMessageDialog(this, "NYI");
        Game.gameOn = true;
        {
            giveUp.setEnabled(true);
            newGame.setEnabled(false);
            newPlayer.setEnabled(false);
            loadDeck.setEnabled(false);
            loadAll.setEnabled(false);
            changeDeck.setEnabled(false);
            showDecks.setEnabled(false);
            removeDeck.setEnabled(false);
            removeAll.setEnabled(false);
            shuffle.setEnabled(false);
            sort.setEnabled(false);
        }
    }//GEN-LAST:event_newGameActionPerformed

    private void quitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_quitActionPerformed
        exit();
        System.exit(0);
    }//GEN-LAST:event_quitActionPerformed

    private void showDecksActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showDecksActionPerformed
        String s = "";
        for (int i = 0; i < decks.size(); i++) {
            s += i + 1 + ": " + decks.get(i).name + " - " + decks.get(i).size() + " card/s\n";
        }
        if (s.equals("")) {
            JOptionPane.showMessageDialog(this, "No decks found");
        } else {
            JOptionPane.showMessageDialog(this, s);
        }
    }//GEN-LAST:event_showDecksActionPerformed

    private void spelPlanKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_spelPlanKeyPressed
    }//GEN-LAST:event_spelPlanKeyPressed

    private void spelPlanMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_spelPlanMouseMoved
        ((SpelPlan) spel).mouseMoved(evt.getX(), evt.getY());
        preview.repaint();
    }//GEN-LAST:event_spelPlanMouseMoved

    private void spelPlanMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_spelPlanMouseClicked
        //((SpelPlan) spelPlan).mouseClicked(evt.getButton());
        //((SpelPlan) spelPlan).mouseMoved(evt.getX(), evt.getY()); // för att uppdatera vilket kort som syns som preview
        //preview.repaint();
    }//GEN-LAST:event_spelPlanMouseClicked

    private void sortActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sortActionPerformed
        if (chosenDeck == null) {
            JOptionPane.showMessageDialog(this, "You have to chose a deck before you sort it..");
            return;
        }
        ArrayList<String> l = new ArrayList<String>();
        String t = "";
        String s = "";
        while (true) {
            s = (String) JOptionPane.showInputDialog(this, "Chose a sorting type 2 times to sort", "Title", JOptionPane.PLAIN_MESSAGE, null, CardList.sort, s);
            if (s == null) {
                return;
            }
            if (s.equals(t)) {
                break;
            }
            l.add(s);
            t = s;
        }
        chosenDeck.sort(l);
        spel.repaint();
        preview.repaint();
    }//GEN-LAST:event_sortActionPerformed

    private void shuffleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_shuffleActionPerformed
        if (chosenDeck == null) {
            JOptionPane.showMessageDialog(this, "You have to chose a deck before you shuffle it..");
            return;
        }
        int ans = JOptionPane.showConfirmDialog(this, "You want to only show the first 7 cards? Yes?");
        if (ans == 2) {
            return;
        }
        chosenDeck.shuffle();
        for (int i = 0; i < chosenDeck.size(); i++) {
            chosenDeck.get(i).marked = true;
            if (i >= 7 && ans == 0) {
                chosenDeck.get(i).facedown = true;
            } else {
                chosenDeck.get(i).facedown = false;
            }
        }
        spel.repaint();
        preview.repaint();
    }//GEN-LAST:event_shuffleActionPerformed

    private void loadAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadAllActionPerformed
        String m = "";
        File[] list = new File("decks/").listFiles();
        ArrayList<String> names = new ArrayList<String>();
        int files = 0;
        for (File f : list) {
            if (f.getName().endsWith(".xml")) {
                try{
                load(f);
                files++;
                }catch(Exception e){
                    JOptionPane.showMessageDialog(this, "Irritating error!");
                }
            }
        }
        if (files < 1) {
            JOptionPane.showMessageDialog(this, "There are no decks to load..");
            return;
        }
    }//GEN-LAST:event_loadAllActionPerformed

    private void removeAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeAllActionPerformed
        if (decks.size() > 0) {
            decks.removeAll(decks);
            setChosenDeck(null);
        } else {
            JOptionPane.showMessageDialog(this, "You don't have any decks to remove...");
            return;
        }
        //Images.savedImages = new ArrayList<Image>();
        JOptionPane.showMessageDialog(this, "All decks have been removed");
    }//GEN-LAST:event_removeAllActionPerformed

    private void giveUpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_giveUpActionPerformed
        {
            newGame.setEnabled(true);
            newPlayer.setEnabled(true);
            giveUp.setEnabled(true);
            loadDeck.setEnabled(true);
            loadAll.setEnabled(true);
            changeDeck.setEnabled(true);
            showDecks.setEnabled(true);
            removeDeck.setEnabled(true);
            removeAll.setEnabled(true);
            shuffle.setEnabled(true);
            sort.setEnabled(true);
        }
    }//GEN-LAST:event_giveUpActionPerformed

    private void fullScreenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fullScreenActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_fullScreenActionPerformed

    private void jRadioButtonMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonMenuItem1ActionPerformed
        jRadioButtonMenuItem1.setSelected(true);
        jRadioButtonMenuItem2.setSelected(false);
        jRadioButtonMenuItem3.setSelected(false);
        ((SpelPlan)spel).setNewCardDimensions(10);
    }//GEN-LAST:event_jRadioButtonMenuItem1ActionPerformed

    private void jRadioButtonMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonMenuItem2ActionPerformed
        jRadioButtonMenuItem1.setSelected(false);
        jRadioButtonMenuItem2.setSelected(true);
        jRadioButtonMenuItem3.setSelected(false);
        ((SpelPlan)spel).setNewCardDimensions(7);
    }//GEN-LAST:event_jRadioButtonMenuItem2ActionPerformed

    private void jRadioButtonMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonMenuItem3ActionPerformed
        jRadioButtonMenuItem1.setSelected(false);
        jRadioButtonMenuItem2.setSelected(false);
        jRadioButtonMenuItem3.setSelected(true);
        ((SpelPlan)spel).setNewCardDimensions(4);
    }//GEN-LAST:event_jRadioButtonMenuItem3ActionPerformed

    private void enter(javax.swing.JButton b) {
        b.setContentAreaFilled(true);
        b.setBorderPainted(true);
    }

    private void exit(javax.swing.JButton b) {
        b.setContentAreaFilled(false);
        b.setBorderPainted(false);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        JFrame.setDefaultLookAndFeelDecorated(true);
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                JFrame self = new MainFrame();
                self.setVisible(true);
                self.requestFocus();
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem about;
    private javax.swing.JMenu cardSize;
    private javax.swing.JMenuItem changeDeck;
    private javax.swing.JPanel confirmBox;
    private javax.swing.JMenuItem fullScreen;
    private javax.swing.JMenuItem giveUp;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenu jMenu4;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItem1;
    private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItem2;
    private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItem3;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JSeparator jSeparator4;
    private javax.swing.JSeparator jSeparator5;
    private javax.swing.JPanel leftSide;
    private javax.swing.JMenuItem loadAll;
    private javax.swing.JMenuItem loadDeck;
    private javax.swing.JMenuItem newGame;
    private javax.swing.JMenuItem newPlayer;
    private javax.swing.JPanel playerLower;
    private javax.swing.JPanel playerUpper;
    private javax.swing.JPanel players;
    private javax.swing.JPanel preview;
    private javax.swing.JMenuItem quit;
    private javax.swing.JMenuItem removeAll;
    private javax.swing.JMenuItem removeDeck;
    private javax.swing.JPanel rightSide;
    private javax.swing.JMenuItem showDecks;
    private javax.swing.JMenuItem shuffle;
    private javax.swing.JMenuItem sort;
    private javax.swing.JPanel spelPlan;
    // End of variables declaration//GEN-END:variables

    private void load(File f) {
        int index = -1;
        CardList gDeck = CardGenerator.getDeck(f);
        if (gDeck != null) {
            for (int j = 0; j < decks.size(); j++) {
                if (gDeck.name.equals(decks.get(j).name)) {
                    index = j;
                    break;
                }
            }
            if (index < 0) {    //behöver inte skriva över
                decks.add(gDeck);
            } else {
                decks.set(index, gDeck);
            }
        } else {
            JOptionPane.showMessageDialog(this, "No deck found in " + f.getName() + "...");
        }
        setChosenDeck(null);
    }

    private void loadDecks(String f) throws IOException, ClassNotFoundException {
        loadDecks(new File(f));
    }

    private void loadDecks(File f) throws IOException, ClassNotFoundException {
        ArrayList<CardList> libs = new ArrayList<CardList>();
        ObjectInputStream in = null;
        try {
            Object obj = null;
            in = new ObjectInputStream(new FileInputStream(f));
            libs = (ArrayList<CardList>) in.readObject();
        } catch (Exception ex) {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
            }
        }
        decks = libs;
        for (CardList cl : decks) {
            for (Card card : cl) {
                card.initImg();
            }
        }
        System.out.println("Loaded decks..");
    }

    private void exit() {
        saveDecks();
    }

    private void saveDecks() {
        try {
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File(deckFile)));
            out.writeObject(decks);
            out.close();
        } catch (IOException ex) {
        }
        System.out.println("Application terminated..");
    }

    private void setChosenDeck(CardList cl) {
        chosenDeck = cl;
    }
}
